//
//  HomeViewController.m
//  FD
//
//  Created by Yasin on 2018/10/10.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//

//布局思路:collectionView来做
//表头
//只显示一个item
//显示两个item
#import "HomeViewController.h"

//view
#import "HomeCustomView.h"
#import "HomeShopcartBtnView.h" //购物车按钮view

//Controller 控制器
//#import "HomeGoodsDetailController.h"
#import "GoodsDetailViewController.h"//商品详情

#import "FDMsgViewController.h"
#import "YuYueListViewController.h" //预约
//#import "RangeNotSupportViewController.h"//超出配送范围
#import "HomeLookDeliveryRangeController.h" //11-27查看配送范围
#import "ShangPinLeiMuViewController.h" //商品类目,点击购物车按钮跳转
#import "FDTabBarController.h"
#import "PersonInfoController.h" //2019-1-21个人资料页面

//点击外送点餐先跳转到 “商品类目” 在跳转到 “外送点餐”
#import "ShangPinLeiMuViewController.h"
#import "WaiSongViewController.h" //外送点餐
#import "FDWebViewController.h" //12-30 轮播图详情页VC

#import "FDNavigationViewController.h"
#import "LoginViewController.h" //2016-2-26 未登录情况下直接跳转到这个页面

//model
#import "HomeModel.h"
#import "HomeWhirligigModel.h"

#import "YingYeShiJianKeFuDianHuaHelper.h"
#import "HomeShopCartHelper.h" //工具类(请求购物数量)
#import <SRWebSocket.h> //11-13 webSocket
//工具类
#import "FDSystemTool.h" //弹框打电话
//#import "FDAWSDownUpLoadTool.h" //12-6下载模板html字符传
//#import "FDWebViewHtmlTool.h"   //12-6保存模板字符到本地

@interface HomeViewController () <HomeCustomViewDelegate,SRWebSocketDelegate>
{
    SRWebSocket *_webSocket;
}

@property (nonatomic, strong) HomeCustomView *homeCustomView;
/**客服电话 10-19 隐藏 */
@property (nonatomic, strong) UIButton *kefuDianHuaBtn;
/**购物车按钮11-27*/
@property (nonatomic, strong) HomeShopcartBtnView *shopcartBtnView;

/**数据源-轮播图*/
@property (nonatomic,  strong) NSMutableArray *whirligigListArr;
/**数据源-热销商品*/
@property (nonatomic,  strong) NSMutableArray *hotScaleListArr;
/**数据源-美味上新*/
@property (nonatomic,  strong) NSMutableArray *newGoodsList;
/**平台客服电话*/
@property (nonatomic, copy) NSString *phone;

/**webSocket*/
@property (nonatomic, strong) SRWebSocket *webSocket;

/**2019-2-26 为了解决这样的需求:跳过的坑 这里记录一下用户id
 只处理这种情况user.id = -1 表示未登录直接跳转到登录页面
 */
@property (nonatomic, strong) NSNumber *tempUserId;
@end

@implementation HomeViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view
    
    [self.view addSubview:self.homeCustomView];
    
    CGFloat x = ([UIScreen mainScreen].bounds.size.width - 80);
    CGFloat y = ([UIScreen mainScreen].bounds.size.height - 150 - FD_TabbarSafeBottomMargin); //iphoneX
    
    self.kefuDianHuaBtn.frame = CGRectMake(10, y, 70, 70);
    [self.view addSubview:self.kefuDianHuaBtn]; //10-19隐藏
    self.shopcartBtnView.frame = CGRectMake(x, y, 70, 70);
    [self.view addSubview:self.shopcartBtnView];
    
    
    //10-20 11:23 接口出问题了
    [self requestHomeData];
    
    FDWeakSelf;
    //客服电话
    [YingYeShiJianKeFuDianHuaHelper obtainKeFuDianHuaBlock:^(NSString * _Nonnull phone) {
        weakSelf.phone = phone;
    }];
    
    //12-6 下载模板字符串html
    [self requestGoodsDetailTemplate];
    
    //12-29 下载轮播图模板字符串。
    [self requestHomeWhirligigTemplate];
    
    
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivePushMsgNotification:) name:kPUSHMSGNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickMineRedDot) name:kClickMineRedNotification object:nil];
}

//收到推送消息,显示小圆点
- (void)receivePushMsgNotification:(NSNotification *)notification {
    [self.homeCustomView showRedDot];
}
- (void)clickMineRedDot {
    [self.homeCustomView hideRedDot];
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    //隐藏导航条
    [self.navigationController setNavigationBarHidden:YES];
    //显示底部tabar
    
    self.hidesBottomBarWhenPushed = YES;
    self.tabBarController.tabBar.hidden = NO;
    self.hidesBottomBarWhenPushed = NO;
    
    //获取购物车数量,(不会循环引用)
    [HomeShopCartHelper shopcartHelperShopcartListBlock:^(NSInteger count) {
        [self.shopcartBtnView updateShopcartBtnViewCount:count];
    }];
    
    //12-3更新首页头像和昵称信息
    [self.homeCustomView updateHomeAvatorAndNickname];
    
    
    [self requestHomeData]; //2019-2-26 为了解决self.tempUserId无法重新赋值问题
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:NO];
}

- (HomeCustomView *)homeCustomView {
    if (!_homeCustomView) {
        _homeCustomView = [[HomeCustomView alloc] initWithFrame:self.view.bounds];
        
        //设置代理
        _homeCustomView.delegate = self;
    }
    return _homeCustomView;
}
- (UIButton *)kefuDianHuaBtn {
    if (!_kefuDianHuaBtn) {
        _kefuDianHuaBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_kefuDianHuaBtn setImage:[UIImage imageNamed:@"kfdhEng"] forState:(UIControlStateNormal)];
        [_kefuDianHuaBtn addTarget:self action:@selector(clickKeFuAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _kefuDianHuaBtn;
}
//h:70,w:70
- (HomeShopcartBtnView *)shopcartBtnView {
    if (!_shopcartBtnView) {
        _shopcartBtnView = [[HomeShopcartBtnView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        _shopcartBtnView.layer.masksToBounds = YES;
        _shopcartBtnView.layer.cornerRadius = 35;
        
        FDWeakSelf;
        _shopcartBtnView.clickShopcartBtnViewBlock = ^{
            [weakSelf skipToShangPinLeiMiVC:YES]; //跳转商品类目页面
        };
    }
    return _shopcartBtnView;
}

- (void)clickKeFuAction:(UIButton *)btn {
    if ([NSString isEmptyString:self.phone]) {
        FDLog(@"电话号码为空,操作无效!");
        return;
    }
    
    [FDSystemTool fd_makePhone:self.phone];
    //    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phone];
    //    UIApplication *application = [UIApplication sharedApplication];
    //    NSURL *URL = [NSURL URLWithString:str];
    //    NSDictionary *dic = @{@"phone":phone};
    //
    //    if (@available(iOS 10.0, *)) {
    //        [application openURL:URL options:dic completionHandler:nil];
    //    } else {
    //        // Fallback on earlier versions
    //    }
}


#pragma mark -  HomeCustomViewDelegate 代理方法
- (void)homeCustomViewDidSelectRowAtIndexPath:(NSIndexPath *)indexPath homeModel:(HomeModel *)model {
    
    NSLog(@"section:%ld---row:%ld",indexPath.section, indexPath.row);
    
    GoodsDetailViewController *goodsDetailVC = [[GoodsDetailViewController alloc] init];
    
    goodsDetailVC.goodsId = model.goodsID; //跳转商品详情
    goodsDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:goodsDetailVC animated:YES];
}


- (void)homeCustomViewClickLocation {
    NSLog(@"%s--%d",__FUNCTION__,__LINE__);
    
    [self.navigationController pushViewController:[[HomeLookDeliveryRangeController alloc] init] animated:YES];
}

- (void)homeCustomViewClickMsg {
    
    //2019-2-20通知我的页面移除小红点
    [[NSNotificationCenter defaultCenter] postNotificationName:kClickHomeRedNotification object:nil];
    
    FDMsgViewController *msgVC = [[FDMsgViewController alloc] init];
    
    [self.navigationController pushViewController:msgVC animated:YES];
}

- (void)homeCustomViewClickWaiMaiDianCan {
    NSLog(@"%s--%d",__FUNCTION__,__LINE__);
    
    //11-19新需求，先跳转 "商品类目" 在跳转 "商品详情"
    //    WaiSongViewController *waiSongVC = [[WaiSongViewController alloc] init];
    //    waiSongVC.hidesBottomBarWhenPushed = YES;
    //    [self.navigationController pushViewController:waiSongVC animated:YES];
    
    [self skipToShangPinLeiMiVC:NO];
}


- (void)skipToShangPinLeiMiVC:(BOOL)isOpen {
    ShangPinLeiMuViewController *shangpinleiMuVC = [[ShangPinLeiMuViewController alloc] init];
    
    if (isOpen == YES) {
        //2019-2-23只有点击了这个按钮，跳转到商品类目页面才自动展开购物车列表
        shangpinleiMuVC.isShangPinLeiMuViewControllerShowCartList = YES;
    }
    
    [self.navigationController pushViewController:shangpinleiMuVC animated:YES];
}

- (void)homeCustomViewClickYuDing {
    NSLog(@"%s--%d",__FUNCTION__,__LINE__);
    
    //跳转预约界面
    YuYueListViewController *yuYueVC = [[YuYueListViewController alloc] init];
    yuYueVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:yuYueVC animated:YES];
}

//12-30点击轮播图
- (void)homeCustomViewClickWhirligigWithResource:(NSString *)resource {
    FDLog(@"lalalal:%@",resource);
    //跳转
    FDWebViewController *whirligigVC = [[FDWebViewController alloc] init];
    whirligigVC.resource = resource;
    [self.navigationController pushViewController:whirligigVC animated:YES];
}

//2019-1-21点击头像跳转到个人资料页面
//!!!!:2019-2-25
- (void)homeCustomViewClickAvatorAction {
    if ([self.tempUserId isEqualToNumber:@(-1)]) { //表示为登录直接模态出来登录页面
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        FDNavigationViewController *navc = [[FDNavigationViewController alloc] initWithRootViewController:loginVC];
        [self presentViewController:navc animated:YES completion:nil];
    }else { //登录状态原逻辑不变
        PersonInfoController *personVC = [[PersonInfoController alloc] init];
        [self.navigationController pushViewController:personVC animated:YES];
    }
}

//!!!!:请求数据
- (void)requestHomeData {
    [FDHttpAPi requestHomeSuccessBlock:^(id responseObjc) {
        //        NSLog(@"第:%d --请求成功:%@",__LINE__,responseObjc);
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:@"SUCCESS"]) { //成功
            
            
            //2019-2-26 标记用户id用于页面跳转 在本类中的这个代理方法中进行使用 homeCustomViewClickAvatorAction
            self.tempUserId = responseObjc[@"data"][@"user"][@"id"];
            
            //解析 轮播图 新上 热门推荐
            NSArray *whirligigList = responseObjc[@"data"][@"whirligigList"];
            for (NSDictionary *dic in whirligigList) {
                HomeWhirligigModel *whirligigModel = [HomeWhirligigModel mj_objectWithKeyValues:dic];
                [self.whirligigListArr addObject:whirligigModel];
            }
            
            NSArray *newArr = responseObjc[@"data"][@"newGoodsList"];
            
            for (NSDictionary *dic2 in newArr) {
                HomeModel *homeModel = [HomeModel mj_objectWithKeyValues:dic2];
                [self.newGoodsList addObject:homeModel];
            }
            
            NSArray *hotArr = responseObjc[@"data"][@"hotSaleGoodsList"];
            for (NSDictionary *dic3 in hotArr) {
                HomeModel *model = [HomeModel mj_objectWithKeyValues:dic3];
                [self.hotScaleListArr addObject:model];
            }
            
            [self.homeCustomView homeCustomReloadDataWithWhirligigArr:self.whirligigListArr hotArr:self.hotScaleListArr newGoodsArr:self.newGoodsList];
            
        }else { //失败 弹框提示
            
        }
        
    } failBlock:^(NSError *error) {
        NSLog(@"");
    }];
}

//!!!!:getter
- (NSMutableArray *)whirligigListArr {
    if (!_whirligigListArr) {
        _whirligigListArr = [NSMutableArray array];
    }
    return _whirligigListArr;
}
- (NSMutableArray *)hotScaleListArr {
    if (!_hotScaleListArr) {
        _hotScaleListArr = [NSMutableArray array];
    }
    return _hotScaleListArr;
}
- (NSMutableArray *)newGoodsList {
    if (!_newGoodsList) {
        _newGoodsList = [NSMutableArray array];
    }
    return _newGoodsList;
}


#pragma mark - 初始化 webSocket


#pragma mark - 12-6 下载模板字符串
/**
 1.登录成功之后就调接口 编号77 获取 templatekey
 2.使用AWS 下载 模板 HTML 字符串,并保存本地
 */
- (void)requestGoodsDetailTemplate {
    //    FDLog(@"调用了该方法");
    //1.获取商品详情模板字符串的 template 字段
    [FDHttpAPi requestGoodsDetailDescribeTemplateSuccessBlock:^(id responseObjc) {
        //有用信息
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            
            NSString *template = responseObjc[@"data"][@"template"];
            
            //            FDLog(@"template:%@",template);
            
            
            //2.使用亚马逊AWS下载模板字符串
            [FDAWSDownUpLoadTool fdAWSDownloadWithKey:template complectionBlock:^(NSString * _Nonnull resultStr) {
                //3.保存模板字符串到本地
                [FDWebViewHtmlTool fdwebViewHtmlSaveTemplateHtml:resultStr];
            } failBlock:^{
                
            }];
            
        }else {
            FDLog(@"加载商品详情模板时出错:%@",responseObjc);
        }
    } failureBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}


#pragma mark - 12-30下载首页轮播图模板
- (void)requestHomeWhirligigTemplate {
    //1.获取首页轮播图模板字符字段 data = {template = "public/1f9c826f0139458c9e48363f99fa8e1f"}
    [FDHttpAPi requestHomeWhirligigTempleateSuccessBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            NSString *template = responseObjc[@"data"][@"template"];
            //2.使用AWS下载轮播图模板字符串
            [FDAWSDownUpLoadTool fdAWSDownloadWithKey:template complectionBlock:^(NSString * _Nonnull resultStr) {
                //3.轮播图模板字符串保存到本地
                [FDWebViewHtmlTool fdwebViewHtmlSaveHomeWhirligigTemplateHtml:resultStr];
            } failBlock:^{
                
            }];
        }else {
            FDLog(@"获取:轮播图模板字符串时出错了:%@",responseObjc[describe]);
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}

#pragma mark - SRWebSocket.h
- (void)setupSocket {
    
    _webSocket.delegate = nil;
    [_webSocket close];
    
    NSURLRequest *req = [FDHttpAPi rb_URLRequestWithUrlAPI:@"/websocket/push"];
    
    _webSocket = [[SRWebSocket alloc] initWithURLRequest:req];
    _webSocket.delegate = self;
    
    [_webSocket open];
}



#pragma mark - SRWebSocketDelegate

//- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
//{
//    NSLog(@"Websocket Connected");
//    self.title = @"Connected!";
//}
//
//- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
//{
//    FDLog(@":( Websocket Failed With Error %@", error);
//
////    self.title = @"Connection Failed! (see logs)";
//    _webSocket = nil;
//}
//- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
//    FDLog(@"Received \"%@\"", message);
//}
//
//
//- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
//{
//    FDLog(@"WebSocket closed");
//    self.title = @"Connection Closed! (see logs)";
//    _webSocket = nil;
//}
//
//- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;
//{
//    FDLog(@"WebSocket received pong");
//}

- (void)dealloc {
    FDLog(@"销毁了");
}

@end


